﻿using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Store.Manager.ERP.Common;
using SqlSugar.Extensions;
namespace Store.Manager.ERP.Api.Helper
{
    public class JwtHelper
    {
        /// <summary>
        /// 颁发
        /// </summary>
        /// <param name="tokenModel"></param>
        /// <returns></returns>
        public static string IssueJwt(JwtToken tokenModel)
        {
            string issuer = AppsettingHelper.app(["Audience", "Issuer"]);
            string audience = AppsettingHelper.app(["Audience", "Audience"]);
            string secret = AppsettingHelper.app(["Audience", "Secret"]);
            string expireHours = AppsettingHelper.app(["Audience", "ExpireHours"]);
            int _expireHours = 0;
            if (!int.TryParse(expireHours, out _expireHours)) { throw new Exception($"配置项错误：{expireHours}"); }
            ;
            var claims = new List<Claim>
            {
                new Claim(JwtRegisteredClaimNames.Jti,tokenModel.Uid),
                new Claim(JwtRegisteredClaimNames.Iat, $"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}"),
                new Claim(JwtRegisteredClaimNames.Nbf,$"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}") ,
                //过期时间，JWT有自己的缓冲过期时间
                new Claim (JwtRegisteredClaimNames.Exp,$"{new DateTimeOffset(DateTime.Now.AddSeconds(_expireHours)).ToUnixTimeSeconds()}"),
                new Claim(ClaimTypes.Expiration, DateTime.Now.AddSeconds(1000).ToString()),
                new Claim(JwtRegisteredClaimNames.Iss,issuer),
                new Claim(JwtRegisteredClaimNames.Aud,audience),
                //自定义key Claim
            };
            #region 角色Claim
            //单角色
            claims.Add(new Claim(ClaimTypes.Role, tokenModel.Role.ToString()));
            //多角色使用如下方法
            //claims.AddRange(tokenModel.Role.Split(',').Select(s => new Claim(ClaimTypes.Role, s)));

            #endregion

            ////密钥(SymmetricSecurityKey 对安全性的要求，密钥的长度太短会报出异常)
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secret));
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            var jwt = new JwtSecurityToken(
                issuer: issuer,
                claims: claims,
                signingCredentials: creds);

            var jwtHandler = new JwtSecurityTokenHandler();
            var encodedJwt = jwtHandler.WriteToken(jwt);

            return encodedJwt;
        }

        /// <summary>
        /// 解析
        /// </summary>
        /// <param name="jwtStr"></param>
        /// <returns></returns>
        public static JwtToken? SerializeJwt(string jwtStr)
        {
            var jwtHandler = new JwtSecurityTokenHandler();
            var canReadToken = jwtHandler.CanReadToken(jwtStr);
            if (canReadToken)
            {
                JwtSecurityToken jwtToken = jwtHandler.ReadJwtToken(jwtStr);
                object? role;
                try
                {
                    jwtToken.Payload.TryGetValue(ClaimTypes.Role, out role);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                    throw;
                }
                if (role == null) { return null; }
                var tm = new JwtToken
                {
                    Uid = (jwtToken.Id).ObjToString(),
                    Role = (JwtRole)Enum.Parse(typeof(JwtRole), role.ToString()),
                };
                return tm;
            }
            else
                return null;
        }
    }
    /// <summary>
    /// 令牌
    /// </summary>
    public class JwtToken
    {
        /// <summary>
        /// userid
        /// </summary>
        public required string Uid { get; set; }
        /// <summary>
        /// 角色
        /// </summary>
        public JwtRole Role { get; set; }
        /// <summary>
        /// 职能
        /// </summary>
        public string? Work { get; set; }
    }

    public enum JwtRole
    {
        Admin,
        Testor,
        SaleDep,
        CaiWuDep,
        CaiGouDep
    }
}
